package leetcode.code0457;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution2 implements IDebug {

	public boolean circularArrayLoop(int[] nums) {
		int len = nums.length;
		int p = 0;
		while (p < len) {
			int cur = nums[p];
			int start = p;
			boolean direction = cur > 0;
			int next = this.next(p, cur, len);
			int count = 0;
			while ((cur = nums[next]) != 0) {
				if ((cur > 0 && direction) || (!direction && cur < 0)) {
					next = this.next(next, cur, len);
					if (count == 0 && start == next) {
						break;
					}
					count++;
					if (count > len) {
						return true;
					}
				} else {
					break;
				}
			}
			p++;
		}
		return false;
	}

	public int next(int cur, int step, int len) {
		int next = cur + step;
		if (next >= 0 && next < len) {
			return next;
		} else if (next >= len) {
			return next % len;
		} else {
			return len + next;
		}
	}

	@Override
	public void debug1() {
		HelpDebug.compare(false, this.circularArrayLoop(HelpDebug.str2array3("[-1,2]")));
	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

		HelpDebug.compare(true, this.circularArrayLoop(HelpDebug.str2array3("[2,-1,1,2,2]")));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub
		HelpDebug.compare(false, this.circularArrayLoop(HelpDebug.str2array3("[-2,1,-1,-2,-2]")));

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub
		HelpDebug.compare(true, this.circularArrayLoop(HelpDebug.str2array3("[1,1,2]")));

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug2();
		so.debug1();
		so.debug4();
		so.debug3();

	}

}
